//
//  MTool.m
//  BMW
//
//  Created by up72-2 on 15/10/26.
//  Copyright © 2015年 up72-2. All rights reserved.
//

#import "MTool.h"
#import "AppDelegate.h"
#import "MAlertView.h"

@implementation MTool



+ (NSString *)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:0 // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    return jsonString;
}

+ (NSMutableDictionary *)jsonStringToDictionary:(NSString *)jsonStr
{
    if (jsonStr == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (void)showMessage:(NSString *)message inView:(UIView *)view
{
    if (!view)
    {
        AppDelegate *app =  (AppDelegate *)[UIApplication sharedApplication].delegate;
        view = app.window;
    }
    
    MAlertView *alertView = [[[NSBundle mainBundle] loadNibNamed:@"MAlertView" owner:nil options:nil] objectAtIndex:0];
    [alertView showWithTitle:message inView:view];
}

+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)size
{
    CGSize textSize = CGSizeZero;
    
    // 7.0 系统的适配处理。
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    textSize = [text boundingRectWithSize:size
                                  options:NSStringDrawingUsesLineFragmentOrigin
                               attributes:tdic
                                  context:nil].size;
    
    return textSize;
}

+(NSData*)returnDataWithDictionary:(NSMutableDictionary*)dict
{
    NSMutableData* data = [[NSMutableData alloc]init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:dict forKey:@"personData"];
    [archiver finishEncoding];
    return data;
}

+(NSMutableDictionary *)returnDictionaryWithDataPath:(NSData *)data
{
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    NSMutableDictionary* myDictionary = [unarchiver decodeObjectForKey:@"personData"];
    [unarchiver finishDecoding];
    return myDictionary;
}

+ (void)deleteFileWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    if (![fileManager removeItemAtPath:path error:&error]) {
        NSLog(@"error = %@", error);
    }
}

+ (BOOL)checkTel:(NSString *)telephone
{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([telephone length] == 0) {
        [MTool showMessage:@"请输入正确的手机号" inView:app.window];
        return NO;
    }
    
    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:telephone];
    
    if (!isMatch) {
        [MTool showMessage:@"请输入正确的手机号" inView:app.window];
        return NO;
    }
    return YES;
}

+ (BOOL)validateEmail:(NSString *)email
{
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:email];
}

+ (BOOL)validateIdentityName: (NSString *)name
{
    BOOL flag;
    NSString *privateName = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (privateName.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^[A-Za-z\u4e00-\u9fa5]+$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:privateName];
}

//存储当前用户数据
+ (BOOL)storeCurrentData:(NSDictionary *)dic
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:dic];
    if (personData) {
        [myDefault setObject:personData forKey:@"loginData"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (NSDictionary *)getCurrentData
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"loginData"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}


//存储用户名
+ (BOOL)storeCurrentUserName:(NSString *)userName
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:userName];
    if (personData) {
        [myDefault setObject:personData forKey:@"userName"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}
+ (NSString *)getUserName
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"userName"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}

//存储用户名
+ (BOOL)storeCurrentState:(NSString *)state
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:state];
    if (personData) {
        [myDefault setObject:personData forKey:@"state"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}
+ (NSString *)getState
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"state"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}


@end
